<?php

namespace app\common\model;

class Article extends BaseModel
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'article';

    // 追加属性
    protected $append = [
        'created_at_text',
        'status_text',
    ];

    // 定义状态
    const STATUS_NORMAL = 1; // 已上架
    const STATUS_HIDDEN = 2; // 已下架

    public static $statusList = [
        self::STATUS_NORMAL => '已上架',
        self::STATUS_HIDDEN => '已下架',
    ];

    // 获取状态文本
    public function getStatusTextAttr($value, $data)
    {
        return isset($data['status']) ? self::$statusList[$data['status']] : '';
    }

    // 获取格式化后的创建时间
    public function getCreatedAtTextAttr($value, $data)
    {
        return isset($data['created_at']) ? date('Y-m-d H:i:s', strtotime($data['created_at'])) : '';
    }

    // 关联分类
    public function category()
    {
        return $this->belongsTo('ArticleCategory', 'category_id', 'id');
    }

    // 获取列表
    public static function getList($where = [], $order = ['weigh' => 'desc', 'created_at' => 'desc'])
    {
        return self::with(['category'])
            ->where($where)
            ->order($order)
            ->paginate();
    }

    // 增加浏览次数（根据IP判断）
    public function incrementViews($ip)
    {
        // 检查是否已经浏览过
        $viewLog = ArticleView::where([
            'article_id' => $this->id,
            'ip' => $ip,
        ])->find();

        if (!$viewLog) {
            // 记录浏览日志
            ArticleView::create([
                'article_id' => $this->id,
                'ip' => $ip,
                'creator' => 'system',
            ]);
            // 增加浏览次数
            return $this->setInc('views');
        }

        return false;
    }

    // 增加点赞次数
    public function incrementLikes()
    {
        return $this->setInc('likes');
    }
}
